package com.czh.gateway.filter;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSON;
import com.czh.gateway.constants.AuthConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * 登录拦截器
 * 将用户id放入请求头以供接下来的服务使用
 * <h4>注意过了gateWay层后URL就不带相应服务的前缀了,所以我决定让这个过滤器先执行</h4>
 * @author caozaihui
 * @version 1.0
 * @since 2024/9/7 下午 6:23
 */
@Component
@Slf4j
public class LoginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        log.info("Gateway:LoginFilter.path-->{}", path);
        //如果属于放行URL列表则放行
        if (AuthConstant.releaseUrlList.contains(path)) {
            return chain.filter(exchange);
        }
        ServerHttpRequest.Builder mutate = request.mutate();
        Object loginId = StpUtil.getLoginId();
        if (Objects.isNull(loginId)) {
            return chain.filter(exchange);
        }
        log.info("Gateway.LoginFilter.loginId-->{}", JSON.toJSON(loginId));
        mutate.header(AuthConstant.USER_CONTEXT_ID, loginId.toString());
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
